package com.sk.ccflower.server.common.tcpManager;

import java.nio.channels.SocketChannel;
import java.util.Date;

import org.apache.log4j.Logger;

import com.sk.ccflower.lib.define.BaseCfg;
import com.sk.ccflower.server.lib.sockUtils.nio.SocketServer;
import com.sk.ccflower.server.lib.sockUtils.nio.SocketSession;

public class TcpManagerSession extends SocketSession {
	
	protected Logger m_log;
	InputDataHandler m_idh = null;
	protected String m_email = null;
	
	public TcpManagerSession(SocketChannel _sc, SocketServer _server) throws Exception {
		super(_sc, _server);
		
		this.m_log = Logger.getLogger( getClass() );
		this.m_idh = new InputDataHandler( this );
		this.m_idh.start();
	}
	
	@Override
	protected void doConnectAction() throws Exception {
		registerTimeout( (BaseCfg.HEART_BEAT_PERIOD*3) );
	}
	
	@Override
	protected void doCloseAction() {
		
	}
	
	@Override
	protected void doTimeoutAction(Date date) {
		m_log.debug(m_sc.socket().getInetAddress().getHostAddress() + ":" + m_sc.socket().getPort() + " 클라이언트 Timeout!");
		removeTimeout();
		close();
	}
	
	@Override
	protected void doRecvAction(byte[] b, int offset, int length) {
		removeTimeout();
		
		m_log.debug( "data received from("+m_sc.socket().getInetAddress().getHostAddress() + ":" + m_sc.socket().getPort()+") : offset("+offset+") length("+length+")" );
		
		try {
			m_idh.doRecvAction(b, offset, length);
		} catch (Exception e) {
			close();
			m_log.error( e );
			e.printStackTrace();
		}
		
		registerTimeout( (BaseCfg.HEART_BEAT_PERIOD*3) );
	}
	
	protected TcpManagerSession findSession( String email ) {
		TcpManagerSession session = ((TcpManagerServer) m_server).findSession( email );
		
		return session;
	}
	
}
